/*
 * Copyright 2008 Carnegie Mellon University
 * Licensed under the Apache License, Version 2.0 (the "License"); 
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *  
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, 
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied. See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
package edu.cmu.lti.sepia.api.html;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import edu.cmu.lti.sepia.data.db.SQL;
import edu.cmu.lti.sepia.data.db.UserDAO;
import edu.cmu.lti.sepia.data.resource.ResourceManager;
import edu.cmu.lti.sepia.infra.system.model.User;
import edu.cmu.lti.sepia.infra.topic.model.Task;

public class UserStatGenerator {

	private static String[] logActions = {"SEARCH","ADD TOPIC","UPDATE TOPIC","DELETE TOPIC",
			"ADD ANSWER TEXT","UPDATE ANSWER TEXT","DELETE ANSWER TEXT","UPDATE ANSWER LABEL",
			"ADD ANSWER NUGGET","DELETE ANSWER NUGGET","UPDATE TASK","DELETE TASK","SAVE VOTE"
			};
	
	public static String printTable( SQL sql, Task task ) throws SQLException {
		List<User> users = UserDAO.getUsers(sql);
		List<User> usersToIgnore = new ArrayList<User>();
		for ( User user : users ) {
			if (user.getUserName().matches("admin|manager")) {
				usersToIgnore.add( user );
			}
		}
		users.removeAll(usersToIgnore);
		Collections.sort(users, new Comparator<User>(){
		    public int compare(User u1, User u2){
		        String val1 = (String) u1.getUserName();
		        String val2 = (String) u2.getUserName();
		        return val1.compareTo(val2);
		    }
		});
		
		String db = ResourceManager.p.getProperty("db_prefix")+"shared";
		String query = "SELECT user_id,count(user_id) FROM "+db+".log WHERE task_id=? AND log_event=? GROUP BY user_id;";
		
		Map<Integer,StringBuilder> userRowMap = new HashMap<Integer,StringBuilder>( users.size() );
		for ( User user : users ) {
			StringBuilder row = new StringBuilder( "<td nowrap>"+user.getUserName()+"</td>\n" );
			userRowMap.put( user.getUserId(), row );
		}
		
		Map<Integer,Integer> userTotalMap = new HashMap<Integer,Integer>( users.size() );
		for ( String a : logActions ) {
			Map<Integer,Integer> userContributionMap = getUserContributionMap( sql, query, task, a );
			for ( User user : users ) {
				StringBuilder row = userRowMap.get(user.getUserId());
				Integer contribution = userContributionMap.get(user.getUserId());
				int c = contribution!=null?contribution:0;
				row.append( "<td align=\"right\">"+c+"</td>" );
				Integer total = userTotalMap.get(user.getUserId());
				userTotalMap.put(user.getUserId(), total!=null?(total+c):c);
			}
		}
		for ( User user : users ) {
			StringBuilder row = userRowMap.get(user.getUserId());
			row.append( "<td align=\"right\">"+userTotalMap.get(user.getUserId())+"</td>\n" );
		}
		
		StringBuilder sb = new StringBuilder();
		sb.append( TableUtil.title(task) );
		
		StringBuilder table = new StringBuilder();
		boolean anyItem = false;
	  table.append( "<table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" class=\"datatable\">" );
	  table.append( TableUtil.thead(logActions) );
    int counter = 0;
		for ( User user : users ) {
			int total = userTotalMap.get(user.getUserId());
			StringBuilder row = userRowMap.get(user.getUserId());
			if ( total > 0 ) {
			  anyItem = true;
	      String className = counter++%2==1?"odd":"even";
	      table.append( "<tr class=\""+className+"\">"+row+"</tr>\n" );
			} else {
			  table.append( "<!--"+row+"-->\n" );
			}
		}
		table.append( "</table>" );
		
		if (anyItem) {
		  sb.append(table);
		} else {
		  sb.append("<div>No activities recorded.</div>");
		}
		return sb.toString();
	}
	
	private static Map<Integer,Integer> getUserContributionMap( SQL sql, 
			String query, Task task, String logAction ) {
		Map<Integer,Integer> result = new HashMap<Integer,Integer>();
		try {
			PreparedStatement ps = sql.getConnection().prepareStatement( query );
			ps.setInt( 1, task.getTaskId() );
			ps.setString( 2, logAction );
			ResultSet rs = sql.executeSelect( ps );
			while (rs.next()) {
				result.put(rs.getInt(1), rs.getInt(2));
			}
			rs.close();
			ps.close();
		} catch ( SQLException e ) {
			e.printStackTrace();
		}
		return result;
	}
	
}
